/*******************************************************************************
*  Project      : Minigate Golfin                                 
*  Program ID   : course_write.js                                 
*  Description  : 코스공략 글쓰기 
*
********************************************************************************
*  Program History                                                            
*  Date        Author    Description                                          
*  ----------  --------  -------------------------------------------------------- 
*  2012-04-30  김효순    Created.  
*  2012-05-02  김효순    Complete.  
*******************************************************************************/

jQuery(function($){
	// 제목
	function clsTitle()
	{
		this._HTMLDom = null;
		this._ERRMSG = {
			"_NOVALUE": "제목을 입력해 주십시요."
		}
		this.errMsg = null;
		this._init();
	}
	
	clsTitle.prototype = {
		_init: function(){
			var $layer = $("div#container section#main_content dl.golf_write dt:first :text");
			this._HTMLDom = {
				"$layer": $layer
			}
		}
		, setValue: function(val){
			this._HTMLDom["$layer"].val(val);
		}
		, getValue: function(){
			return this._HTMLDom["$layer"].val();
		}
		, getError: function(){
			return this.errMsg;
		}
		, isValid: function(){
			var $layer = this._HTMLDom["$layer"];
			
			if($layer.val() == ""){
				this.errMsg = this._ERRMSG["_NOVALUE"];
				return false;
			}
			
			return true;
		}
		, focus: function(){
			this._HTMLDom["$layer"].focus();
		}
	}
	
	// 골프장
	function clsGolfList()
	{
		this._HTMLDom = null;
		this.listData = null;
		this.idx = null;
		this.bLoad = null;
		
		this._ERRMSG = {
			"_NOVALUE": "골프장을 선택해 주십시요."
		}
		this.errMsg = null;
		
		this._init();
	}
	
	clsGolfList.prototype = {
		_init: function(){
			var $layer = $("div#container section#main_content dl.golf_write dt:eq(1) div.selectlayer02:eq(0)");
			this._HTMLDom = {
				"$layer": $layer
				, "$element": $layer.find("li:first").clone(true)
			}
			
			$layer.find("p.default:first a").click(function(event){
				event.preventDefault();
				
				$layer.find("ul").show(300);
			});
			
			this.bLoad = false;
			
			this.reset();
		}
		, reset: function(){
			this.listData = [{
				"키": ""
				, "골프장명": "골프장 선택"
			}];
			this.display();
			this.setIdx(0);
		}
		, setList: function(thisData){
			this.listData = this.listData.concat(thisData);
			this.display();
			
			this.bLoad = true;
		}
		, display: function(){
			var $layer = this._HTMLDom["$layer"];
			var $element = this._HTMLDom["$element"];
			var thisClass = this;
			
			$layer.find("ul").empty();
			for(var i=0;i<this.listData.length;i++){
				$layer.find("ul").append($element.clone(true));
			}
			$layer.find("li").each(function(n){
				$(this).find("a").html(thisClass.listData[n]["골프장명"]).click(function(event){
					event.preventDefault();
					if(n == thisClass.idx){
						$layer.find("ul").hide(300);
					}else{
						thisClass.setIdx(n);
					}
				});
			});
		}
		, displayTitle: function(){
			this._HTMLDom["$layer"].find("p.default:first a").html(this.listData[this.idx]["골프장명"]);
		}
		, setIdx: function(idx){
			this.idx = idx;
			this.displayTitle();
			this._HTMLDom["$layer"].find("ul").hide(300);
			
			$(this).trigger("evtGolfSet");
		}
		, getError: function(){
			return this.errMsg;
		}
		, getValue: function(){
			return this.listData[this.idx]["키"];
		}
		, setValue: function(key){
			for(var i=0;i<this.listData.length;i++){
				if(this.listData[i]["키"] == key) break;
			}
			
			if(i < this.listData.length) this.setIdx(i);
			else this.setIdx(0);
		}
		, isValid: function(){
			if(!this.idx || this.idx == 0){
				this.errMsg = this._ERRMSG["_NOVALUE"];
				return false;
			}
			
			return true;
		}
		, isLoaded: function(){
			return this.bLoad;
		}
	}
	
	// 홀
	function clsHoleList()
	{
		this._HTMLDom = null;
		this.listData = null;
		this.idx = null;
		this.bLoad = null;
		
		this._ERRMSG = {
			"_NOVALUE": "홀을 선택해 주십시요."
		}
		this.errMsg = null;
		
		this._init();
	}
	
	clsHoleList.prototype = {
		_init: function(){
			var $layer = $("div#container section#main_content dl.golf_write dt:eq(1) div.selectlayer02:eq(1)");
			this._HTMLDom = {
				"$layer": $layer
				, "$element": $layer.find("li:first").clone(true)
			}
			
			$layer.find("p.default:first a").click(function(event){
				event.preventDefault();
				
				$layer.find("ul").show(300);
			});
			
			this.reset();
		}
		, reset: function(){
			this.listData = [{
				"키": ""
				, "홀명": "홀 선택"
			}];
			this.bLoad = false;
			this.display();
			this.setIdx(0);
		}
		, setList: function(thisData){
			this.listData = this.listData.concat(thisData);
			this.display();
			this.bLoad = true;
		}
		, display: function(){
			var $layer = this._HTMLDom["$layer"];
			var $element = this._HTMLDom["$element"];
			var thisClass = this;
			
			$layer.find("ul").empty();
			for(var i=0;i<this.listData.length;i++){
				$layer.find("ul").append($element.clone(true));
			}
			$layer.find("li").each(function(n){
				$(this).find("a").html(thisClass.listData[n]["홀명"]).click(function(event){
					event.preventDefault();
					if(n == thisClass.idx){
						$layer.find("ul").hide(300);
					}else{
						thisClass.setIdx(n);
					}
				});
			});
		}
		, displayTitle: function(){
			this._HTMLDom["$layer"].find("p.default:first a").html(this.listData[this.idx]["홀명"]);
		}
		, setIdx: function(idx){
			this.idx = idx;
			this.displayTitle();
			this._HTMLDom["$layer"].find("ul").hide(300);
			
			$(this).trigger("evtHoleSet");
		}
		, getError: function(){
			return this.errMsg;
		}
		, getValue: function(){
			return this.listData[this.idx]["키"];
		}
		, setValue: function(key){
			for(var i=0;i<this.listData.length;i++){
				if(this.listData[i]["키"] == key) break;
			}
			
			if(i < this.listData.length) this.setIdx(i);
			else this.setIdx(0);
		}
		, isValid: function(){
			if(!this.idx || this.idx == 0){
				this.errMsg = this._ERRMSG["_NOVALUE"];
				return false;
			}
			
			return true;
		}
		, isLoaded: function(){
			return this.bLoad;
		}
	}
	
	// 홀이미지
	function clsHoleImage()
	{
		this._HTMLDom = null;
		this.imageInfo = null;
		
		this._init();
	}
	
	clsHoleImage.prototype = {
		_init:function(){
			var $layer = $("div#container section#main_content dl.golf_write dd:eq(0)");
			this._HTMLDom = {
				"$layer": $layer
			}
			
			this.reset();
		}
		, reset: function(){
			this._HTMLDom["$layer"].hide();
		}
		, setInfo: function(thisData){
			this.imageInfo = thisData;
			this.display();
		}
		, display: function(){
			var $layer = this._HTMLDom["$layer"];
			
			$layer.find("img").attr("src", this.imageInfo["이미지"]);
			$layer.show(300);
		}
		, getValue: function(){
			return this.imageInfo["이미지"];
		}
	}
	
	// 내용
	function clsNote()
	{
		this._HTMLDom = null;
		this._init();
	}
	
	clsNote.prototype = {
		_init: function(){
			var $layer = $("div#container section#main_content dl.golf_write dd:eq(1)");
			this._HTMLDom = {
				"$layer": $layer
			}
			$layer.html("<textarea></textarea>");
			$layer.find("textarea").ckeditor({
				toolbar: [
					{ name: 'document', items : [ 'Source','-','NewPage','DocProps','Preview','Print','-','Templates' ] },
					{ name: 'clipboard', items : [ 'Cut','Copy','Paste','PasteText','PasteFromWord','-','Undo','Redo' ] },
					{ name: 'editing', items : [ 'Find','Replace','-','SelectAll','-','SpellChecker', 'Scayt' ] },
					{ name: 'colors', items : [ 'TextColor','BGColor' ] },
					{ name: 'tools', items : [ 'Maximize', 'ShowBlocks' ] },
					{ name: 'insert', items : [ 'Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak','Iframe' ] },
					{ name: 'forms', items : [ 'Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'HiddenField' ] },
					{ name: 'basicstyles', items : [ 'Bold','Italic','Underline','Strike','Subscript','Superscript','-','RemoveFormat' ] },
					{ name: 'paragraph', items : [ 'NumberedList','BulletedList','-','Outdent','Indent','-','Blockquote','CreateDiv',
					'-','JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock','-','BidiLtr','BidiRtl' ] },
					{ name: 'links', items : [ 'Link','Unlink','Anchor' ] },
					{ name: 'styles', items : [ 'Styles','Format','Font','FontSize' ] }
				]
			});
		}
		, insertHoleImage: function(szImage){
			var $layer = this._HTMLDom["$layer"];
			var val = $layer.find("textarea").val();
			
			if(val) val = "<br><br>" + val;
			
			this.$getEditor().val("<img src='" + szImage + "' />" + val);
		}
		, focus: function(){
			this.$getEditor().ckeditorGet().focus();
		}
		, $getEditor: function(){
			return this._HTMLDom["$layer"].find("textarea");
		}
		, getValue: function(){
			return this.$getEditor().val();
		}
		, setValue: function(val){
			this.$getEditor().val(val);
		}
	}
	
	function clsComm()
	{
		this.golfList = null;
		this.courseData = null;
		this.holeList = null;
		this.holeRequest = null;
		this.holeImageData = null;
		this.holeImageRequest = null;
		
		this._init();
	}
	
	clsComm.prototype = {
		_init: function(){
			this.golfList = [
				{
					"키": null
					, "골프장명": null
				}
			];
			
			this.courseData = {
				"제목": null
				, "작성자": {
					"아이디": null
					, "이미지": null
					, "닉네임": null
				}
				, "골프장명": null
				, "코스명": null
				, "홀명": null
				, "작성일": null
				, "작성시": null
				, "조회수": null
				, "내용": null
				, "댓글수": null
			}
			
			this.holeList = [
				{
					"키": null
					, "홀명": null
				}
			];
			
			this.holeImageData = {
				"이미지": null
			}
		}
		, getGolfList: function(){
			var thisClass = this;
			
			//ajax
			setTimeout(function(){
				thisClass.golfList = [
					{
						"키": "001"
						, "골프장명": "골프장1"
					}
					, {
						"키": "002"
						, "골프장명": "골프장2"
					}
					, {
						"키": "003"
						, "골프장명": "골프장3"
					}
					, {
						"키": "004"
						, "골프장명": "골프장4"
					}
					, {
						"키": "005"
						, "골프장명": "골프장5"
					}
					, {
						"키": "006"
						, "골프장명": "골프장6"
					}
				];
				
				$(thisClass).trigger("evtFinishGolfList");
			}, 500);
		}
		, getGolfData: function(){
			return this.golfList;
		}
		, getCourseInfo: function(q_seq){
			var thisClass = this;
			
			//ajax
			setTimeout(function(){
				thisClass.courseData = {
					"제목": "제목이 노출됩니다. 제목이 노출됩니다. 제목이 노출됩니다. 제목이 노출됩니다. 제목이 노출됩니다.111"
					, "작성자": {
						"아이디": "sky72"
						, "이미지": "../images/board/default_50_50.gif"
						, "닉네임": "오스케 짱말짱짱말짱"
					}
					, "골프장키": "001"
					, "홀키": "001"
					, "이미지": "../images/board/del.gif"
					, "작성일": "2012-03-03"
					, "작성시": "17:35"
					, "조회수": 256
					, "내용": "코스 위에 정지하여 있는 흰 볼을 지팡이 모양의 클럽으로 잇달아 쳐서 정해진 홀(球孔)에 넣어 그때까지 소요된 타수(打數)의 많고 적음으로 우열을 겨루는 경기이다. 골프코스는 들판·구릉·산림 등 66만∼100만㎡의 넓은 지역을 이용하여 정형(整形)되어 있고, 해변에 만들어지는 시사이드 코스와 내륙에 만들어지는 인랜드 코스가 있다."
					, "댓글수": 2
				}
				
				$(thisClass).trigger("evtFinishCourseInfo");
			}, 1500);
		}
		, getCourseData: function(){
			return this.courseData;
		}
		, getHoleList: function(golfKey){
			var thisClass = this;
			this.holeRequest = golfKey;
			
			//ajax
			//beforeSend로 전송 확인
			setTimeout(function(){
				thisClass.holeList = [
					{
						"키": "001"
						, "홀명": "홀1"
					}
					, {
						"키": "002"
						, "홀명": "홀2"
					}
					, {
						"키": "003"
						, "홀명": "홀3"
					}
					, {
						"키": "004"
						, "홀명": "홀4"
					}
					, {
						"키": "005"
						, "홀명": "홀5"
					}
					, {
						"키": "006"
						, "홀명": "홀6"
					}
				];
				
				$(thisClass).trigger("evtFinishHoleList");
			}, 500);
		}
		, getHoleData: function(){
			return this.holeList;
		}
		, getHoleImageInfo: function(golfKey, holeKey){
			var thisClass = this;
			this.holeImageRequest = {
				"골프키": golfKey
				, "홀키": holeKey
			}
			
			//ajax
			//beforeSend로 전송 확인
			setTimeout(function(){
				thisClass.holeImageData = {
					"이미지": "../images/board/del.gif"
				}
				
				$(thisClass).trigger("evtFinishHoleImageInfo");
			}, 500);
		}
		, getHoleImageData: function(){
			return this.holeImageData;
		}
		, getCourseSubmit: function(arg){
			var thisClass = this;
			
			/*arg = {
				"키": null
				, "제목": null
				, "골프장키": null
				, "홀키": null
				, "내용": null
			}*/
			
			//ajax
			setTimeout(function(){
				var ret = {
					"처리결과": "001"
					, "메시지": null
				}
				
				$(thisClass).trigger("evtFinishCourseSubmit", [ret]);
			}, 1500);
		}
	}
	
	// 컨트롤
	function clsControl()
	{
		this.objComm = null;
		this.objTitle = null;
		this.objGolfList = null;
		this.objHoleList = null;
		this.objHoleImage = null;
		this.objNote = null;
		
		this._init();
	}
	
	clsControl.prototype = {
		_init: function(){
			this.objComm = new clsComm();
			this.objTitle = new clsTitle();
			this.objGolfList = new clsGolfList();
			this.objHoleList = new clsHoleList();
			this.objHoleImage = new clsHoleImage();
			this.objNote = new clsNote();
			
			this._bind();
			
			// 골프장 리스트
			this.objComm.getGolfList();
			
			if(document.objUtil.getParam("q_seq")){
				document.objGlobal.spinStart();
				this.objComm.getCourseInfo();
			}
		}
		, _bind: function(){
			var thisClass = this;
			
			// 코스정보 완료
			$(this.objComm).bind("evtFinishCourseInfo", function(){
				var thisData = this.getCourseData();
				
				document.objGlobal.spinEnd();

				thisClass.objTitle.setValue(thisData["제목"]);
				thisClass.setGolfValue(thisData["골프장키"]);
				thisClass.setHoleValue(thisData["홀키"]);
				thisClass.objNote.setValue(thisData["내용"]);
				
			// 골프장 리스트 완료
			}).bind("evtFinishGolfList", function(){
				var thisData = this.getGolfData();
				
				thisClass.objGolfList.setList(thisData);
			// 홀리스트 완료
			}).bind("evtFinishHoleList", function(){
				var thisData = this.getHoleData();
				
				thisClass.objHoleList.setList(thisData);
			// 홀 이미지 완료
			}).bind("evtFinishHoleImageInfo", function(){
				var thisData = this.getHoleImageData();
				
				thisClass.objHoleImage.setInfo(thisData);
			// 글쓰기 완료
			}).bind("evtFinishCourseSubmit", function(){
				var ret = arguments[1];
				
				alert("글작성이 완료되었습니다.");
				document.location.href = "course.html?q_my=" + document.objUtil.getParam("q_my");
			});
			
			// 골프장선택
			$(this.objGolfList).bind("evtGolfSet", function(){
				// 홀리스트 받아오기
				var thisKey = this.getValue();
				
				thisClass.objHoleList.reset();
				
				if(thisKey){
					thisClass.objComm.getHoleList(thisKey);
				}
			});
			
			// 홀선택
			$(this.objHoleList).bind("evtHoleSet", function(){
				// 이미지 받아오기
				var golfKey = thisClass.objGolfList.getValue();
				var holeKey = this.getValue();
				
				if(golfKey && holeKey){
					thisClass.objComm.getHoleImageInfo(golfKey, holeKey);
				}else{
					thisClass.objHoleImage.reset();
				}
			});
			
			// 에디터 준비완료
			this.objNote.$getEditor().ckeditorGet().on("instanceReady", function(){
				
			});
			
			// 글쓰기
			$("img[alt=확인]").parent().click(function(event){
				event.preventDefault();
				
				// check valid
				if(!thisClass.objTitle.isValid()){
					alert(thisClass.objTitle.getError());
					return;
				}else if(!thisClass.objGolfList.isValid()){
					alert(thisClass.objGolfList.getError());
					return;
				}else if(!thisClass.objHoleList.isValid()){
					alert(thisClass.objHoleList.getError());
					return;
				}
				
				document.objGlobal.spinStart("sending...");
				thisClass.objComm.getCourseSubmit({
					"키": null
					, "제목": thisClass.objTitle.getValue()
					, "골프장키": thisClass.objGolfList.getValue()
					, "홀키": thisClass.objHoleList.getValue()
					, "내용": thisClass.objNote.getValue()
				});
			});
			
			// 이미지 삽입
			$("div#container section#main_content dl.golf_write dt:eq(1) :image").click(function(event){
				event.preventDefault();
				
				thisClass.objNote.insertHoleImage(thisClass.objHoleImage.getValue());
			});
		}
		, setGolfValue: function(key){
			var thisClass = this;
			
			if(this.objGolfList.isLoaded()){
				this.objGolfList.setValue(key);
			}else{
				setTimeout(function(){
					thisClass.setGolfValue(key);
				}, 100);
			}
		}
		, setHoleValue: function(key){
			var thisClass = this;
			
			if(this.objHoleList.isLoaded()){
				this.objHoleList.setValue(key);
			}else{
				setTimeout(function(){
					thisClass.setHoleValue(key);
				}, 100);
			}
		}
	}
	
	document.objControl = new clsControl();
});